package com.egao.common.manage.school;

import com.egao.common.core.annotation.ApiPageParam;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.aolan.service.AoLanService;
import com.egao.common.module.student.constants.StudentSignConstants;
import com.egao.common.module.student.entity.StudentSign;
import com.egao.common.module.student.entity.StudentSignAlter;
import com.egao.common.module.student.entity.vo.StudentCollegeVO;
import com.egao.common.module.student.entity.vo.StudentSignAdminListVO;
import com.egao.common.module.student.entity.vo.StudentSignConfirmVO;
import com.egao.common.module.student.service.StudentService;
import com.egao.common.module.student.service.StudentSignAlterService;
import com.egao.common.module.student.service.StudentSignService;
import com.egao.common.module.system.constants.UserConstants;
import com.egao.common.module.system.service.CollegeService;
import com.egao.common.module.system.service.MajorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 校毕业去向管理
 * @author lym
 */
@Api(tags = "校毕业去向管理")
@RestController
@RequestMapping("${api}")
public class SchoolSignController extends BaseController {

    @Autowired
    private StudentSignService studentSignService;
    @Autowired
    private CollegeService collegeService;
    @Autowired
    private MajorService majorService;
    @Autowired
    private AoLanService aoLanService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentSignAlterService studentSignAlterService;

    private final String title = "校毕业去向管理";

    /**
     * 梁老师工号
     * 校级管理列表 已签约、邀约记录 梁老师不区分学生学历本研
     * 其他正常区分
     */
    private String LIANG_TEACHER = "Z0003981";

    @PreAuthorize("hasAuthority('school:sign:list')")
    @OperLog(value = title, desc = "分页查询毕业去向")
    @ApiOperation(value = "分页查询毕业去向")
    @ApiPageParam
    @GetMapping("/school/sign/page")
    public PageResult<StudentSignAdminListVO> page(HttpServletRequest request) {
        PageParam<StudentSignAdminListVO> pageParam = new PageParam<>(request);
        String degree = null;
        degree = UserConstants.DEGREE_SCOPE_ALL.equals(getLoginUser().getDegreeScope()) ? null : getLoginUser().getDegreeScope();
        pageParam.put("degree", degree);
        pageParam.put("user", "school");

        String category = pageParam.getString("category");
        if (StudentSignConstants.ADMIN_LIST_CATEGORY_4.equals(category) || StudentSignConstants.ADMIN_LIST_CATEGORY_5.equals(category)) {
            if (LIANG_TEACHER.equals(getLoginUser().getUsername())) {
                pageParam.put("degree", null);
            }
        }
        return studentSignService.listAdminPage(pageParam);
    }

    @PreAuthorize("hasAuthority('school:sign:list')")
    @ApiOperation(value = "查询所有学院")
    @GetMapping("/school/sign/colleges")
    public JsonResult colleges() {
        return JsonResult.ok().setData(collegeService.listAll(null, ""));
    }

    @PreAuthorize("hasAuthority('school:sign:list')")
    @ApiOperation(value = "查询所有专业")
    @GetMapping("/school/sign/majors")
    public JsonResult majors() {
        return JsonResult.ok().setData(majorService.listAll("", null));
    }

    @PreAuthorize("hasAuthority('school:sign:detail')")
    @OperLog(value = title, desc = "查询详情")
    @ApiOperation("查询详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "Integer")
    })
    @GetMapping("/school/sign/detail")
    public JsonResult detail(Integer id) {
        return studentSignService.detail(id, null, false, getLoginUser().getUserType());
    }

    @PreAuthorize("hasAuthority('school:sign:detail')")
    @OperLog(value = title, desc = "选择录用方式", result = true)
    @ApiOperation(value = "选择录用方式")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentSign", value = "studentSign", required = true, dataType = "studentSign")
    })
    @PutMapping("/school/sign/pick-dispatch-hired-way")
    public JsonResult pickDispatchHiredWay(@RequestBody StudentSign studentSign) {
        return studentSignService.pickDispatchHiredWay(studentSign, studentSign.getUserId());
    }

    @PreAuthorize("hasAuthority('school:sign:update')")
    @OperLog(value = title, desc = "修改学生毕业去向登记", result = true)
    @ApiOperation(value = "修改学生毕业去向登记")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentSign", value = "studentSign", required = true, dataType = "studentSign")
    })
    @PutMapping("/school/sign/submit")
    public JsonResult submit(@RequestBody StudentSign studentSign) {
        return studentSignService.submitForSchool(studentSign, getLoginUserId());
    }

    @PreAuthorize("hasAuthority('school:sign:export')")
    @OperLog(value = title, desc = "导出", result = true)
    @ApiOperation(value = "导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "StudentExcelVO", value = "StudentExcelVO", required = false, dataType = "StudentExcelVO")
    })
    @GetMapping("/school/sign/export")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        PageParam<StudentSignAdminListVO> pageParam = new PageParam<>(request);
        String degree = null;
        degree = UserConstants.DEGREE_SCOPE_ALL.equals(getLoginUser().getDegreeScope()) ? null : getLoginUser().getDegreeScope();
        pageParam.put("degree", degree);
        pageParam.put("user", "college");

        String category = pageParam.getString("category");
        if (StudentSignConstants.ADMIN_LIST_CATEGORY_4.equals(category) || StudentSignConstants.ADMIN_LIST_CATEGORY_5.equals(category)) {
            if (LIANG_TEACHER.equals(getLoginUser().getUsername())) {
                pageParam.put("degree", null);
            }
        }
        studentSignService.exportStudentSign(pageParam, response);
    }

    @PreAuthorize("hasAuthority('school:sign:detail')")
    @ApiOperation("协议就业打印表")
    @ApiPageParam
    @PostMapping("/school/sign/print/deal")
    public JsonResult dealPrint(@RequestBody StudentSign studentSign) {
        if (studentSign == null || studentSign.getId() == null) {
            throw new BusinessException("参数异常");
        }
        return studentSignService.dealPrint(studentSign.getId(), null);
    }

    @PreAuthorize("hasAuthority('school:sign:detail')")
    @ApiOperation("灵活就业打印表")
    @ApiPageParam
    @PostMapping("/school/sign/print/agile")
    public JsonResult agilePrint(@RequestBody StudentSign studentSign) {
        if (studentSign == null || studentSign.getId() == null) {
            throw new BusinessException("参数异常");
        }
        return studentSignService.agilePrint(studentSign.getId(), null);
    }

    @PreAuthorize("hasAuthority('school:sign:detail')")
    @ApiOperation("自由职业打印表")
    @ApiPageParam
    @PostMapping("/school/sign/print/free")
    public JsonResult freePrint(@RequestBody StudentSign studentSign) {
        if (studentSign == null || studentSign.getId() == null) {
            throw new BusinessException("参数异常");
        }
        return studentSignService.freePrint(studentSign.getId(), null);
    }

    @PreAuthorize("hasAuthority('school:sign:detail')")
    @ApiOperation("自主创业打印表")
    @ApiPageParam
    @PostMapping("/school/sign/print/venture")
    public JsonResult venturePrint(@RequestBody StudentSign studentSign) {
        if (studentSign == null || studentSign.getId() == null) {
            throw new BusinessException("参数异常");
        }
        return studentSignService.venturePrint(studentSign.getId(), null);
    }

    @PreAuthorize("hasAuthority('school:sign:update')")
    @OperLog(value = title, desc = "推送奥兰", result = true)
    @ApiOperation(value = "推送奥兰")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "Integer")
    })
    @GetMapping("/school/sign/ao-lan")
    public JsonResult aoLan(Integer id) {
        StudentSign studentSign = studentSignService.getById(id);
        return aoLanService.insert(studentSign);
    }

    @PreAuthorize("hasAuthority('school:sign:update')")
    @OperLog(value = title, desc = "重置就业方式", result = true)
    @ApiOperation(value = "重置就业方式")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "毕业去向主键ID", required = true, dataType = "Integer")
    })
    @GetMapping("/school/sign/reset")
    public JsonResult reset(Integer id) {
        return studentSignService.resetSignCategoryBySchool(id, getLoginUserId());
    }

    @PreAuthorize("hasAuthority('school:sign:list')")
    @ApiOperation(value = "学院确认毕业去向人数集合")
    @GetMapping("/school/sign/confirm-list")
    public JsonResult confirmList(Integer yearId) {
        List<StudentCollegeVO> studentCollegeVOList = studentService.studentCollegeList(yearId);
        List<StudentSignConfirmVO> studentSignConfirmVOList = studentSignService.studentSignConfirmList(yearId);

        List<StudentSignConfirmVO> list = studentCollegeVOList.stream()
                .map(item -> new StudentSignConfirmVO(item.getCollegeCode(), item.getCollegeName(), item.getStudentCount())).collect(Collectors.toList());

        for (StudentSignConfirmVO all : list) {
            for (StudentSignConfirmVO sign : studentSignConfirmVOList) {
                if (all.getCollegeCode().equals(sign.getCollegeCode())) {
                    all.setConfirmCount(sign.getConfirmCount());
                    all.setConfirmNoCount(all.getStudentCount() - sign.getConfirmCount());
                }
            }
        }

        return JsonResult.ok().setData(list);
    }

    @PreAuthorize("hasAuthority('school:sign:list')")
    @ApiOperation(value = "档案转递单位名称变动记录")
    @GetMapping("/school/sign/alter-list")
    public JsonResult alterList(Integer studentSignId) {
        List<StudentSignAlter> list = studentSignAlterService.listByStudentSignId(studentSignId);
        return JsonResult.ok().setData(list);
    }

    @PreAuthorize("hasAuthority('school:sign:list')")
    @OperLog(value = title, desc = "导入", result = true)
    @ApiOperation("导入")
    @Transactional
    @PostMapping("/school/sign/import-number")
    public JsonResult importBatch(MultipartFile file) {
        return studentSignService.importNumber(file);
    }
}
